package map.editor;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import map.PlayingField;

public class MapEditor extends JFrame implements Runnable, ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7553669787164221781L;
	
	public static void main( String[] args )
	{
		( new Thread( new MapEditor() ) ).start();
	}
	/**
	 * 
	 */
	
	private double time;
	
	private View view;
	private JToolBar terrain;
	private JButton grass;
	private JButton brown;
	private JMenuItem open;
	private JMenuItem save;
	private JMenuItem exit;
	
	private MiniMapViewer miniMap;
	
	public MapEditor()
	{
		this.setSize( 500, 500 );
		
		view = new View();
		
		grass = new JButton( new ImageIcon( "Images/grassTile.png" ) );
		brown = new JButton( new ImageIcon( "Images/brownTile.png" ) );
		
		open = new JMenuItem( "Open..." );
		save = new JMenuItem( "Save As..." );
		exit = new JMenuItem( "Exit" );
		
		JMenu file = new JMenu( "File" );
		file.add( open );
		file.add( save );
		file.add( exit );
		
		JMenuBar menu = new JMenuBar();
		menu.add( file );
		
		this.setJMenuBar( menu );
		
		grass.addActionListener( this );
		brown.addActionListener( this );
		open.addActionListener( this );
		save.addActionListener( this );
		exit.addActionListener( this );
		
		terrain = new JToolBar( "Terrain" ); 
		terrain.add( grass );
		terrain.add( brown );
		
		this.add( terrain, BorderLayout.PAGE_START );
		this.add( view, BorderLayout.CENTER );
		
		miniMap = new MiniMapViewer( this );
		
		time = System.currentTimeMillis();
		
		this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
		this.setVisible( true );
	}
	
	@Override
	public void run() 
	{
		while( true )
		{
			double duration = ( System.currentTimeMillis() - time ) / 1000.0;
			
			view.update( duration );
			view.repaint();
			
			time = System.currentTimeMillis();
			
			try 
			{
				Thread.sleep( 20 );
			} 
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public void actionPerformed( ActionEvent e )
	{
		Object o = e.getSource();
		if( o.equals( grass ) )
		{
			view.setCurrentTile( PlayingField.tileG );
		}
		else if( o.equals( brown ) )
		{
			view.setCurrentTile( PlayingField.tileB );
		}
		else if( o.equals( open ) )
		{
			view.open();
		}
		else if( o.equals( save ) )
		{
			view.save();
		}
		else if( o.equals( exit ) )
		{
			System.exit( 0 );
		}
	}
}
